import React, { useEffect, useRef } from 'react';
import { Card, Spin, Empty, Tooltip } from 'antd';

interface DataItem {
  name: string;
  value: number;
  color: string;
}

interface PieChartProps {
  title: string;
  data: DataItem[];
  loading?: boolean;
  height?: number;
  showLegend?: boolean;
}

const PieChart: React.FC<PieChartProps> = ({
  title,
  data,
  loading = false,
  height = 300,
  showLegend = true,
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    if (!loading && data.length > 0 && canvasRef.current) {
      const canvas = canvasRef.current;
      const ctx = canvas.getContext('2d');
      
      if (ctx) {
        // 清除画布
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        // 计算总值
        const total = data.reduce((sum, item) => sum + item.value, 0);
        
        // 设置圆心和半径
        const centerX = canvas.width / 2;
        const centerY = canvas.height / 2;
        const radius = Math.min(centerX, centerY) - 40;
        
        // 绘制饼图
        let startAngle = 0;
        data.forEach((item) => {
          // 计算弧度
          const angle = (item.value / total) * Math.PI * 2;
          const endAngle = startAngle + angle;
          
          // 绘制扇形
          ctx.beginPath();
          ctx.moveTo(centerX, centerY);
          ctx.arc(centerX, centerY, radius, startAngle, endAngle);
          ctx.closePath();
          ctx.fillStyle = item.color;
          ctx.fill();
          
          // 绘制边框
          ctx.strokeStyle = '#fff';
          ctx.lineWidth = 2;
          ctx.stroke();
          
          // 绘制标签
          if (angle > 0.2) { // 只有当扇形足够大时才显示标签
            const labelRadius = radius * 0.7;
            const labelAngle = startAngle + angle / 2;
            const labelX = centerX + Math.cos(labelAngle) * labelRadius;
            const labelY = centerY + Math.sin(labelAngle) * labelRadius;
            
            ctx.fillStyle = '#fff';
            ctx.font = 'bold 14px Arial';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText(`${Math.round((item.value / total) * 100)}%`, labelX, labelY);
          }
          
          startAngle = endAngle;
        });
        
        // 绘制图例
        if (showLegend) {
          const legendX = canvas.width - 100;
          const legendWidth = 80;
          let legendY = 30;
          
          data.forEach((item) => {
            // 绘制颜色方块
            ctx.fillStyle = item.color;
            ctx.fillRect(legendX, legendY, 15, 15);
            
            // 绘制边框
            ctx.strokeStyle = '#ddd';
            ctx.lineWidth = 1;
            ctx.strokeRect(legendX, legendY, 15, 15);
            
            // 绘制文本
            ctx.fillStyle = '#333';
            ctx.font = '12px Arial';
            ctx.textAlign = 'left';
            ctx.textBaseline = 'middle';
            
            // 截断长文本
            let label = item.name;
            if (label.length > 10) {
              label = label.substring(0, 8) + '...';
            }
            
            ctx.fillText(`${label} (${item.value})`, legendX + 20, legendY + 7);
            
            legendY += 25;
          });
        }
      }
    }
  }, [data, loading, showLegend]);

  return (
    <Card title={title} style={{ marginBottom: 16 }}>
      {loading ? (
        <div style={{ height, display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
          <Spin />
        </div>
      ) : data.length === 0 ? (
        <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" style={{ height, display: 'flex', flexDirection: 'column', justifyContent: 'center' }} />
      ) : (
        <canvas ref={canvasRef} width={600} height={height} style={{ width: '100%', height: 'auto' }} />
      )}
    </Card>
  );
};

export default PieChart; 